"use client"

import { useState, useEffect } from "react"
import { AlbumCategories } from "@/components/album/album-categories"
import { Button } from "@/components/ui/button"
import { ChevronLeft, ChevronRight, Loader2 } from "lucide-react"
import { fetchAlbums } from "@/lib/api-client"
import type { Album } from "@/types/album"
import { AlbumCard } from "@/components/album-card"
import { RegionLanguageFilter } from "@/components/filters/region-language-filter"
import { LanguageId, RegionId } from "@/types/region-language"
import type { AlbumGenreId } from "@/types/album-genre"

export default function AlbumsPage() {
  const [selectedLanguageId, setSelectedLanguageId] = useState<LanguageId>(LanguageId.ALL)
  const [selectedRegionId, setSelectedRegionId] = useState<RegionId>(RegionId.ALL)
  const [selectedGenreId, setSelectedGenreId] = useState<AlbumGenreId | null>(null)
  const [featuredAlbums, setFeaturedAlbums] = useState<Album[]>([])
  const [albums, setAlbums] = useState<Album[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const itemsPerPage = 5
  const [albumsCurrentPage, setAlbumsCurrentPage] = useState(1)
  const [albumsTotalPages, setAlbumsTotalPages] = useState(1)
  const [, setAlbumsTotalCount] = useState(0)

  // 获取精选专辑
  useEffect(() => {
    const getFeaturedAlbums = async () => {
      try {
        const response = await fetchAlbums({
          page: currentPage,
          limit: itemsPerPage,
          featured: true,
          regionId: selectedRegionId !== RegionId.ALL ? selectedRegionId : undefined,
          languageId: selectedLanguageId !== LanguageId.ALL ? selectedLanguageId : undefined,
        })

        // 假设API返回的数据格式为 { items: Album[], total: number, page: number, limit: number }
        setFeaturedAlbums(response.items)
        setTotalPages(Math.ceil(response.total / itemsPerPage))
      } catch (err) {
        console.error("获取精选专辑失败:", err)
        setError("获取精选专辑失败，请稍后再试")
      }
    }

    getFeaturedAlbums()
  }, [selectedRegionId, selectedLanguageId, currentPage, itemsPerPage])

  // 获取所有专辑
  useEffect(() => {
    const getAlbums = async () => {
      setIsLoading(true)
      try {
        const response = await fetchAlbums({
          page: albumsCurrentPage,
          limit: 20,
          regionId: selectedRegionId !== RegionId.ALL ? selectedRegionId : undefined,
          genreId: selectedGenreId,
          languageId: selectedLanguageId !== LanguageId.ALL ? selectedLanguageId : undefined,
        })

        // 假设API返回的数据格式为 { items: Album[], total: number, page: number, limit: number }
        setAlbums(response.items)
        setAlbumsTotalCount(response.total)
        setAlbumsTotalPages(Math.ceil(response.total / response.limit))
        setError(null)
      } catch (err) {
        console.error("获取专辑列表失败:", err)
        setError("获取专辑列表失败，请稍后再试")
      } finally {
        setIsLoading(false)
      }
    }

    getAlbums()
  }, [selectedRegionId, selectedGenreId, selectedLanguageId, albumsCurrentPage])

  // 处理翻页
  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1)
    }
  }

  // 处理语言选择变化
  const handleLanguageChange = (languageId: LanguageId) => {
    setSelectedLanguageId(languageId)
    setCurrentPage(1) // 重置精选专辑页码
    setAlbumsCurrentPage(1) // 重置全部专辑页码
  }

  // 处理地区选择变化
  const handleRegionChange = (regionId: RegionId) => {
    setSelectedRegionId(regionId)
    setCurrentPage(1) // 重置精选专辑页码
    setAlbumsCurrentPage(1) // 重置全部专辑页码
  }

  const handleNextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1)
    }
  }

  const handleAlbumsPrevPage = () => {
    if (albumsCurrentPage > 1) {
      setAlbumsCurrentPage(albumsCurrentPage - 1)
    }
  }

  const handleAlbumsNextPage = () => {
    if (albumsCurrentPage < albumsTotalPages) {
      setAlbumsCurrentPage(albumsCurrentPage + 1)
    }
  }

  return (
      <div className="min-h-screen">
        <div className="container mx-auto px-4 py-6">
          {/* 语言和地区筛选 */}
          <RegionLanguageFilter
              onLanguageChange={handleLanguageChange}
              onRegionChange={handleRegionChange}
              initialLanguageId={selectedLanguageId}
              initialRegionId={selectedRegionId}
          />

          {/* 精选专辑 */}
          <div className="mb-8">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold">精选专辑</h2>
            </div>
            <div className="relative">
              {/* 左侧翻页按钮 - 第一页不显示 */}
              {currentPage > 1 && (
                  <button
                      onClick={handlePrevPage}
                      className="absolute left-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                      aria-label="上一页"
                  >
                    <ChevronLeft className="h-6 w-6 text-primary" />
                  </button>
              )}

              {/* 专辑列表 */}
              <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
                {featuredAlbums.map((album) => (
                    <AlbumCard key={album.id} album={album} />
                ))}
              </div>

              {/* 右侧翻页按钮 */}
              {currentPage < totalPages && (
                  <button
                      onClick={handleNextPage}
                      className="absolute right-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                      aria-label="下一页"
                  >
                    <ChevronRight className="h-6 w-6 text-primary" />
                  </button>
              )}
            </div>
          </div>

          {/* 专辑分类 */}
          <div className="mb-8">
            <h2 className="text-2xl font-bold mb-4">专辑分类</h2>
            <AlbumCategories
                selectedGenreId={selectedGenreId}
                onGenreChange={(genreId) => {
                  setSelectedGenreId(genreId)
                  setAlbumsCurrentPage(1) // 重置全部专辑页码
                }}
            />
          </div>

          {/* 全部专辑 */}
          <div>
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold">全部专辑</h2>
              <div className="flex space-x-2">
                <Button variant="outline" size="sm">
                  最新
                </Button>
                <Button variant="outline" size="sm">
                  最热
                </Button>
              </div>
            </div>

            {isLoading ? (
                <div className="flex justify-center items-center h-60">
                  <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                </div>
            ) : error ? (
                <div className="flex justify-center items-center h-60 text-red-500">{error}</div>
            ) : (
                <div className="relative">
                  {/* 左侧翻页按钮 - 第一页不显示 */}
                  {albumsCurrentPage > 1 && (
                      <button
                          onClick={handleAlbumsPrevPage}
                          className="absolute left-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                          aria-label="上一页"
                      >
                        <ChevronLeft className="h-6 w-6 text-primary" />
                      </button>
                  )}

                  {/* 专辑列表 */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
                    {albums.map((album) => (
                        <AlbumCard key={album.id} album={album} />
                    ))}
                  </div>

                  {/* 右侧翻页按钮 */}
                  {albumsCurrentPage < albumsTotalPages && (
                      <button
                          onClick={handleAlbumsNextPage}
                          className="absolute right-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                          aria-label="下一页"
                      >
                        <ChevronRight className="h-6 w-6 text-primary" />
                      </button>
                  )}
                </div>
            )}
          </div>
        </div>
      </div>
  )
}

